package com.cn.jdia.sc;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class QuotaUpdate {

	public static void update(String config, String quota) {

		String serverName = null;
		String ip = null;

		String[] conlist = config.split("\n");
		for (int i = 0; i < conlist.length; i++) {
			if (conlist[i].startsWith("SERVERNAME")) {
				serverName = conlist[i].substring(conlist[i].indexOf(":") + 1);
			} else if (conlist[i].startsWith("IP")) {
				ip = conlist[i].substring(conlist[i].indexOf(":") + 1);
			}

		}

		System.out.println(serverName);
		System.out.println(ip);

		System.out.println("------------");

		DBManager4Mysql db = DBManager4Mysql.createInstance();
		db.connectDB();

		String del = "delete from serverdisk where servername='" + serverName + "' and serverip='" + ip + "'";
		int delret = db.executeUpdate(del);
		System.out.println(delret);

		Map<String, String> mem = new HashMap<>();
		List<String> cpu = new ArrayList<>();

		String insert = null;

		String[] quotalist = quota.split("\n");
		for (int i = 0; i < quotalist.length; i++) {
			if (quotalist[i].startsWith("DISK")) {
				System.out.println(quotalist[i].split(" ")[1] + " : " + quotalist[i].split(" ")[2]);

				insert = "insert into serverdisk value('" + serverName + "','" + ip + "','" + quotalist[i].split(" ")[1]
						+ "','" + quotalist[i].split(" ")[2] + "')";
				db.executeUpdate(insert);

			} else if (quotalist[i].startsWith("Mem")) {
				mem.put("total", quotalist[i].split(" ")[1]);
				mem.put("used", quotalist[i].split(" ")[2]);
			} else if (quotalist[i].startsWith("CPUFREE")) {
				cpu.add(quotalist[i].split(" ")[1]);
			}
		}

		System.out.println(mem.toString());
		System.out.println(cpu.toString());

		del = "delete from serverquota where servername='" + serverName + "' and serverip='" + ip + "'";
		delret = db.executeUpdate(del);
		System.out.println(delret);

		insert = "insert into serverquota value('" + serverName + "','" + ip + "'," + mem.get("total") + ","
				+ mem.get("used") + ",'" + cpu.get(0) + "','" + cpu.get(1) + "','" + cpu.get(2) + "','" + cpu.get(3)
				+ "','" + cpu.get(4) + "')";
		int inret = db.executeUpdate(insert);

		db.closeDB();

	}
}
